import requests
import json
#import openpyxl
from openpyxl import load_workbook,Workbook
import sys
import threading
from collections import deque

def car_ABC(cla = 'A'):

    '''
    {A:[
    {Brand: "A - 奥迪",
    Url: "/Images/Logo/aodi.png", ImageUrl: null},
    …],

    …}

    '''
    #以首字母分类汽车品牌
    url_ABC = 'https://item.tuhu.cn/Car/GetCarBrands2?callback=__GetCarBrands__&_=1539332427966'

    r = requests.get(url_ABC)
    #info_ABC = r.json()
    info_ABC = r.text.replace('__GetCarBrands__(','')[:-1]#r.json()
    x = json.loads(info_ABC)
    return x[cla]


def car_info(car = 'A+-+奥迪'):

    url = 'https://item.tuhu.cn/Car/SelOneBrand'
    payload = dict(callback='__GetCarBrands__',
                   Brand=car,
                   )
    r = requests.get(url,params = payload)
    info_car = r.text.replace('__GetCarBrands__(','')[:-1]#r.json()
    x = json.loads(info_car)["OneBrand"]
    return x

def car_pailiang(VehicleID='VE-AUDF96AE'):

    url ='https://item.tuhu.cn/Car/SelectVehicle'

    payload = dict(callback='__GetCarBrands__',
                   VehicleID=VehicleID,
                   )
    
    r = requests.get(url,params = payload)
    #print(r.url)
    info_car = r.text.replace('__GetCarBrands__(','')[:-1]#r.json()
    x = json.loads(info_car)
    if x['PaiLiang']:

        return x['PaiLiang']
    else:
        return '没有排量数据'

def car_year(VehicleID = 'VE-AUDF96AE' ,pailiang = '1.8L'):

    url = 'https://item.tuhu.cn/Car/SelectVehicle'

    payload = dict(callback='__GetCarBrands__',
                   VehicleID=VehicleID,
                   PaiLiang=pailiang
                   )

    r = requests.get(url,params = payload)
    info_car = r.text.replace('__GetCarBrands__(','')[:-1]#r.json()
    x = json.loads(info_car)
    return x


def save_info(car = 'A+-+奥迪'):#传入一个品牌，下载改品牌所有车型

    '''
    [{'Vehicle': '100-一汽大众奥迪', 'ProductID': 'VE-AUDF96AE',
    'BrandType': '一汽大众奥迪', 'Brand': 'A - 奥迪',
    'Url': '/Images/Logo/aodi.png',
    'Src': 'https://img2.tuhu.org/Images/type/VE-AUDF96AE.png@163w_163h_100Q.png',
    'IsBaoYang': 'True', 'CarName': '100', 'appSrc': None,
    'Image': 'https://img2.tuhu.org/Images/type/VE-AUDF96AE.png@100Q.png',
    'ImageUrl': 'https://img2.tuhu.org/Images/Logo/AoDi.png',
    'Tires': '195/70R14;185/70R14;195/65R15', 'SpecialTireSize': None,
    'OriginalIsBaoyang': 1, 'Priority2': 2, 'Priority3': 0, 'VehicleSeries': None},
    '''

    wb = Workbook()
    sheet = wb.active
    sheet.title = "New Shit"
    for i in car_info(car):
        
        
        pailiang = car_pailiang(VehicleID = i['ProductID'])

        '''
        {'TipsInfo': '', 'Code': '1',
        'PaiLiang': [{'Key': 'VE-AUDF96AE','Value': '1.8L'}, {'Key': 'VE-AUDF96AE', 'Value': '2.0L'},
        {'Key': 'VE-AUDF96AE', 'Value': '2.2L'},
        {'Key': 'VE-AUDF96AE', 'Value': '2.6L'}]}
        
        '''
        if pailiang == '没有排量数据':

            #break
            continue
        
        for val in pailiang:
            
            
            max_row = sheet.max_row+1
            sheet['A{}'.format(max_row)] = i['Brand']  #汽车品牌
            sheet['B{}'.format(max_row)] = i['Vehicle']    #车型
            sheet['C{}'.format(max_row)] = i['BrandType']#生产厂家 
            sheet['D{}'.format(max_row)] = val['Value'] #排量

            year = car_year(VehicleID = i['ProductID'] ,pailiang = val['Value'])['Nian']
            '''

            {
            'TipsInfo': '',
            'Code': '1',
            'Nian': [
            {'Key': 'VE-AUDF96AE', 'Value': '1996'},
            {'Key': 'VE-AUDF96AE', 'Value': '1995'},
            {'Key': 'VE-AUDF96AE', 'Value': '1994'},
            {'Key': 'VE-AUDF96AE', 'Value': '1993'},

            {'Key': 'VE-AUDF96AE', 'Value': '1992'}
                    ]

            }'''
            year_str = ''
            for prduce_year in year:
                year_str = year_str + prduce_year['Value'] + ','
            
            sheet['E{}'.format(max_row)] = year_str

        

        #try:    
            print('{}-排量:{} 写入完成'.format(i['Vehicle'],val['Value']))
        #except 
    wb.save('途虎-{}-汽车车型.xlsx'.format(i['Brand']))


def duo_xian():
    while True:
        if not li:
            break
        site = li.popleft()

        for car_brand in car_ABC(site):

            try:

                save_info(car_brand['Brand'].strip().replace(' ','+'))

            except:

                lock.acquire()

                with open('Error_site.txt','a') as f:
                    f.write('{}\n'.format(site))
                            
                    f.write(str(sys.exc_info()))
                    print(sys.exc_info())
                    f.write('\n')
                    f.write('*'*20+'\n')

                lock.release()

def my_thread(thread_num = 26):#最多26线程OK
      
    global li,lock
    lock = threading.Lock()   
    li = deque([chr(i) for i in range(ord("A"),ord("Z")+1)])
    pool = []
    for i in range(thread_num):
        pool.append(threading.Thread(target = duo_xian))
    for i in pool:
        i.start()
    for i in pool:
        i.join()
        
        
    
    


if __name__ == '__main__':

    #print(car_info(car = 'P+-+帕加尼'))
    #print(car_info())
    #print(car_pailiang('VE-PAGZONDA'))

    #save_info(car = 'P+-+帕加尼')
    my_thread()
    



    
    
        
    
    

    
    





























    
    

